/**
 * Created with IntelliJ IDEA.
 * User: aermakov
 * Date: 20.05.13
 * Time: 16:03
 * To change this template use File | Settings | File Templates.
 */

var DH = GrailsCompany.data.DH;
GrailsCompany.Loaders = Ext.define(null, {
    Employee: new Ext.tree.TreeLoader({
        directFn: function (nodeId, fn) {
            var items = [];
            DH.Stores.Employee.query('parentId', nodeId).each(function (it) {
                items.push({
                    id: it.data.id,
                    recordId: it.id,
                    parentId: it.data.parentId,
                    storeId: DH.Stores.Employee.storeId,
                    text: it.data.firstName + ' ' + it.data.lastName,
                    leaf: true,
                    nodeType: 'async'
                });
            }, this);
            fn(items, {status: true});
        }
    }),
    Project: new Ext.tree.TreeLoader({
        directFn: function (nodeId, fn) {
            var items = [];
            DH.Stores.Project.query('parentId', nodeId).each(function (it) {
                items.push({
                    id: it.data.id,
                    recordId: it.id,
                    parentId: it.data.parentId,
                    storeId: DH.Stores.Project.storeId,
                    text: it.data.title,
                    leaf: true,
                    expandable: true,
                    loader: Loaders.Employee,
                    nodeType: 'async'
                });
            }, this);
            fn(items, {status: true});
        }
    }),
    Department: new Ext.tree.TreeLoader({
        directFn: function (nodeId, fn) {
            var items = [];
            DH.Stores.Department.query('parentId', nodeId).each(function (it) {
                items.push({
                    id: it.data.id,
                    recordId: it.id,
                    parentId: it.data.parentId,
                    storeId: DH.Stores.Department.storeId,
                    text: it.data.title,
                    leaf: true,
                    expandable: true,
                    loader: Loaders.Project,
                    nodeType: 'async'
                });
            }, this);
            fn(items, {status: true});
        }
    }),
    Organization: new Ext.tree.TreeLoader({
        directFn: function (nodeId, fn) {
            var items = [];
            DH.Stores.Organization.each(function (record) {
                items.push({
                    id: record.data.id,
                    recordId: record.id,
                    storeId: DH.Stores.Organization.storeId,
                    text: record.data.title,
                    leaf: true,
                    expandable: true,
                    loader: Loaders.Department,
                    nodeType: 'async'
                });
            }, this);
            fn(items, {status: true});
        }
    })
});
var Loaders = new GrailsCompany.Loaders();

var treePanel = {
    id: 'dataTree',
    region: 'west',
    xtype: 'treepanel',
    autoScroll: true,
    columnWidth: .3,
    height: 400,
    root: new Ext.tree.AsyncTreeNode(),
    rootVisible: false,
    loader: Loaders.Organization,
    selModel: new Ext.tree.MultiSelectionModel,
    useArrows: true,
    nodeTypes: {
        'node': Ext.tree.TreeNode,
        'async': Ext.tree.AsyncTreeNode
    },
    listeners: {
        click: function (node) {
            var store = Ext.StoreMgr.get(node.attributes.storeId);
            var record = store.getById(node.attributes.recordId);
            FH.showDetails(node.attributes.storeId, record);
        },
        contextmenu: function (node, e) {
            e.stopEvent();
            if (node.leaf) {
                treeMenu.node = node;
                treeMenu.store = Ext.StoreMgr.get(node.attributes.storeId);
                treeMenu.showAt(e.xy);
            }
        }
    },
    bubbleEvents: ['statusUpdate']
};

var treeMenu = new Ext.menu.Menu({
    items: [
        {
            xtype: 'menuitem',
            tpl: 'Create {label}',
            itemId: 'create',
            data: ''
        },
        {
            xtype: 'menuitem',
            tpl: 'Create {label}',
            itemId: 'createchild',
            data: ''
        },
        {
            xtype: 'menuitem',
            tpl: 'Delete {label}',
            itemId: 'delete',
            data: ''
        }
    ],
    listeners: {
        itemclick: function (item) {
            switch (item.itemId) {
                case 'create':
                    FH.showCreate(this.store.storeId);
                    break;
                case 'createchild':
                    FH.showCreate(this.store.childStoreId);
                    break;
                case 'delete':
                    DH.delete(this.store.storeId, this.node.attributes.recordId)
            }
        },

        beforeshow: function () {
            var createchild = this.items.get('createchild');
            createchild.setVisible(this.store.childStoreId);
        },

        show: function () {
            this.items.get('create').update({label: this.store.label});
            this.items.get('delete').update({label: this.store.label});
            var createchild = this.items.get('createchild');
            if (createchild.isVisible()) {
                var childstore = Ext.StoreMgr.get(this.store.childStoreId);
                createchild.update({label: childstore.label});
            }
        }
    }
});

DH.on('update', function (record, storeId, action, text) {
    var tree = Ext.getCmp('dataTree');
    var root = tree.getRootNode();
    var child = root.findChildBy(function (n) {
        return n.attributes.id === record.data.id && n.attributes.storeId === storeId;
    }, this, true);

    switch (action) {
        case 'delete':
            if (child) {
                child.remove(true);
            }
            break;
        case 'update':
            if (child) {
                var text = storeId === DH.Stores.Employee.storeId
                    ? (record.data.firstName + ' ' + record.data.lastName)
                    : record.data.title;
                child.setText(text);
            }
            break;
        case 'create':
            var store = Ext.StoreMgr.get(storeId);
            var parentStoreId = store.parentStoreId;
            var parent = root;
            if (parentStoreId) {
                parent = root.findChildBy(function (n) {
                    return (n.attributes.id == record.data.parentId
                        && n.attributes.storeId === parentStoreId);
                }, this, true);
            }
            if (!parent) {
                break;
            }
            var expanded = parent.isExpanded();
            parent.reload();
            if (expanded) {
                parent.expand();
            }
            break;
    }
});